package com.gameloops;

public class Gameloop2 extends Thread {
	/* difference between time of update and world step time */
    float localTime = 0f;
    private final int MAXSUBSTEPS = 5;
    private final float FIXEDTIMESTEP = 1 / 60f;
    
    public Gameloop2()
    {
    	//this.setDaemon(true);
    }
	
	@Override
	public void run()
	{
		long start = System.nanoTime();
        while (true) {
            long now = System.nanoTime();
            float elapsed = (now - start) / 1000000000f;
            start = now;
            internalUpdateWithFixedTimeStep(elapsed, MAXSUBSTEPS, FIXEDTIMESTEP);
            if (1000000000 * FIXEDTIMESTEP - (System.nanoTime() - start) > 1000000) {
                try {
                    Thread.sleep(0, 999999);
                } catch (InterruptedException ex) {
                }
            }
        }
	}
	
	/**
     * Updates game state if possible and sets localTime for interpolation.
     * @param elapsedSeconds
     * @param maxSubSteps
     * @param fixedTimeStep 
     */
    private void internalUpdateWithFixedTimeStep(float elapsedSeconds, int maxSubSteps, float fixedTimeStep) {
        int numSubSteps = 0;
        if (maxSubSteps != 0) {
            // fixed timestep with interpolation
            localTime += elapsedSeconds;
            if (localTime >= fixedTimeStep) {
                numSubSteps = (int) (localTime / fixedTimeStep);
                localTime -= numSubSteps * fixedTimeStep;
            }
        }
        if (numSubSteps != 0) {
            // clamp the number of substeps, to prevent simulation grinding spiralling down to a halt
            int clampedSubSteps = (numSubSteps > maxSubSteps) ? maxSubSteps : numSubSteps;
            for (int i = 0; i < clampedSubSteps; i++) {
                update(fixedTimeStep);
            }
        }
    }
    
    /**
     * update game. elapsedTime is fixed.  (override/replace)
     * @param elapsedTime 
     */
    protected void update(float elapsedTime) {
    	// positie += speed * elapsedTime
    	System.out.println("FPS: " + 1 / elapsedTime);
    }
}
